<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";

// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 2. 封装初始化图表的函数（复用）
const initChart = (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  const option = {
    legend: {
      show: true,
      left: 0,
      top: "center",
      orient: "vertial", // 图例列表的布局朝向
      formatter: function (name) {
        const value = props.data.find((item) => item.name === name).value;
        return `{name|${name}}\n{value|${value}}`;
      },
      itemGap: 10,
      itemWidth: 12,
      itemHeight: 12,
      textStyle: {
        rich: {
          name: {
            fontSize: 12,
            color: "#262626",
            padding: [16, 0, 0, 0],
          },
          value: {
            fontSize: 14,
            color: "#262626",
            padding: [3, 0, 0, 0],
          },
        },
      },
    },
    tooltip: {
      trigger: "item",
      formatter: "{b} : {c} ({d}%)",
    },
    plotOptions: {
      pie: {
        borderRadius: 5,
        dataLabels: [
          {
            enabled: true,
            distance: "-30%",
            filter: {
              property: "percentage",
              operator: ">",
              value: 5,
            },
            format: "{point.y:.1f}%",
            style: {
              fontSize: "0.9em",
              textOutline: "none",
            },
          },
        ],
      },
    },
    series: [
      {
        name: "",
        label: {
          show: true,
          position: "inside",
          formatter: "{d}%",
          fontSize: 12,
          color: "#fff",
        },
        padAngle: 3,
        type: "pie",
        data: props.data,
      },
    ],
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

watch(
  () => props.data,
  () => initChart()
);
</script>

<style scoped>
.chart-container {
  width: 100%; /* 自适应父容器宽度 */
  height: 100%;
}
</style>
